<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/14 0014
 * Time: 上午 9:05
 */

namespace app\admin\controller;


use app\admin\model\CategoryModule;
use app\admin\model\LessonContentList;
use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;
use think\Exception;

class Lesson extends BasicAdmin
{
    public $table = 'Lesson';
    public $content = 'LessonContentList';
    public function index(){
        $this->title = '课程列表';
        $db = \app\admin\model\Lesson::where(['is_deleted'=>1,'type'=>12])->field('id,sort,status,title,cover,create_at,keywords,is_recommend')->order('sort asc,id asc');
        $get = $this->request->get();
        foreach (['title', 'keywords'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }
        return parent::_list($db);
    }

    public function add(){
        if ($this->request->isPost()){
            $post = $this->request->post();
            $post['desc'] = json_encode(array_values($post['desc']), 320);
            $post['cover_desc'] = json_encode($post['cover_desc'], 320);
            $post['leidatu'] = json_encode(array_values($post['leidatu']), 320);
            cache('leidatu',$post['leidatu']);
            cache('desc',$post['desc']);
            $post['pid'] = implode(',',$post['pid']);
            $post['type'] = 12;
            if (empty($post['pid'])){
                $this->error('请选择分类');
            }
            Db::startTrans();
            try{
                $id = Db::name('lesson')->insertGetId($post);
                $list_data = [
                    [
                        'title'=>'课程简介',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'kechengjianjie'
                    ],
                    [
                        'title'=>'课程收获',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'kechengxiangqing'
                    ],
                    [
                        'title'=>'课程特色',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'xingqianzhunbei'
                    ],
                    [
                        'title'=>'课程内容',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'kechenganpai'
                    ],
                    [
                        'title'=>'服务标准',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'zhuyishixiang'
                    ],
                    [
                        'title'=>'安全保障',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'anquanbaozhang'
                    ],
                ];
                Db::name('lesson_content_list')->insertAll($list_data);
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $this->error('保存失败，请稍候重试！');
            }
            $this->success('保存成功！', '');
        }
        $lesson_cate = \app\admin\model\LessonCate::where(['pid'=>0,'is_deleted'=>1])->field('id,name')->order('sort asc,id asc')->select();
        $this->assign([
            'title'=>'添加课程',
            'cate'=>$lesson_cate,
            'desc'=>json_decode(cache('desc'),true),
            'leidatu'=>json_decode(cache('leidatu'),true)
        ]);
        return view();
    }

    //编辑简要信息
    public function edit(){
        if ($this->request->isPost()){
            $post = $this->request->post();
            $post['desc'] = json_encode(array_values($post['desc']), 320);

            $post['cover_desc'] = json_encode($post['cover_desc'], 320);
            $post['leidatu'] = json_encode(array_values($post['leidatu']), 320);

            cache('leidatu',$post['leidatu']);
            cache('desc',$post['desc']);
            $post['pid'] = implode(',',$post['pid']);
            if (empty($post['pid'])){
                $this->error('请选择分类');
            }
            Db::name('lesson')->update($post);
            $this->success('保存成功！', '');
        }
        $id = $this->request->get('id');
        $db = \app\admin\model\Lesson::get($id)->toArray();
        $db['pid'] = explode(',',$db['pid']);
        $db['cover_desc'] = json_decode($db['cover_desc'], true);
        $db['desc'] = json_decode($db['desc'], true);
        $db['leidatu'] = json_decode($db['leidatu'], true);

        $lesson_cate = \app\admin\model\LessonCate::where(['pid'=>0,'is_deleted'=>1])->field('id,name')->order('sort asc,id asc')->select();
        $this->assign([
            'db'=>$db,
            'title'=>'编辑',
            'cate'=>$lesson_cate
        ]);
        return view();
    }

    /**
     * 分类禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (DataService::update($this->table)) {
            $this->success("禁用成功！", '');
        }
        $this->error("禁用失败，请稍候再试！");
    }

    /**
     * 分类启用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        if (DataService::update($this->table)) {
            $this->success("启用成功！", '');
        }
        $this->error("启用失败，请稍候再试！");
    }

    /**
     * 删除分类
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (DataService::update($this->table)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

    //选择分类ajax
    public function cate2(){
        $pid = $this->request->post('pid');
        $lesson_cate = \app\admin\model\LessonCate::where(['is_deleted'=>1])->field('id,name,pid')->order('sort asc,id asc')->select()->toArray();
        $lesson_cate = ToolsService::arr2tree($lesson_cate,'id','pid','children');
        $cate = [];
        foreach ($lesson_cate as $k=>$v){
            if ($v['id']==$pid && isset($v['children'])){
                $cate = $v['children'];
            }
        }
        if (!empty($cate)){
            return ['code'=>1,'data'=>$cate];
        }else{
            return ['code'=>2];
        }
    }

    //内容列表
    public function content(){
        $pid = $this->request->get('id');
        $this->title = Db::name('lesson')->where(['id' => $pid, 'is_deleted' => 1])->value('title') . ' - 内容详情';
        $db = Db::name('lesson_content_list')->where(['pid'=>$pid,'is_deleted'=>1])->hidden('content')->order('sort asc,id asc');
        return parent::_list($db,true,true,false,array("pid"=>$pid));
    }

    public function contentadd(){
        $intId = $this->request->get('id');
        if ($this->request->isPost()){
            $post = $this->request->post();
            $post['title'] = $post['content'][0]['title'];
            $post['content'] = json_encode($post['content'], 320);
            foreach ($post as $k=>$v){
                if (strpos($k,'_editor_upload')!==false){
                    unset($post[$k]);
                }
            }
            $post['pid'] = $intId;
            $post['create_at'] = date("Y-m-d H:i:s",time());
            $post['type'] = "kechengjianjie";

            unset($post['id']);

                Db::name('lesson_content_list')->insertGetId($post,false,"id");
            $this->success('保存成功', '');
        }

        $this->assign([
            'title'=>'添加',
            'id'=>$intId,
        ]);
        return view("contentadd");
    }

    public function contentedit(){
        if ($this->request->isPost()){
            $post = $this->request->post();
            $post['title'] = $post['content'][0]['title'];
            $post['content'] = json_encode($post['content'], 320);
            foreach ($post as $k=>$v){
                if (strpos($k,'_editor_upload')!==false){
                    unset($post[$k]);
                }
            }
            Db::name('lesson_content_list')->update($post);
            $this->success('保存成功', '');
        }
        $id = $this->request->get('id');
        $db = Db::name('lesson_content_list')->where(['id' => $id, 'is_deleted' => 1])->find();
        $db['content'] = json_decode($db['content'], true);
        $this->assign([
            'title'=>$db['title'],
            'vo'=>$db
        ]);
        return view($db['type']);
    }

    public function contenttitle(){
        return $this->_form($this->content);
    }

    /**
     * 分类禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function content_forbid()
    {
        if (DataService::update($this->content)) {
            $this->success("禁用成功！", '');
        }
        $this->error("禁用失败，请稍候再试！");
    }

    /**
     * 分类启用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function content_resume()
    {
        if (DataService::update($this->content)) {
            $this->success("启用成功！", '');
        }
        $this->error("启用失败，请稍候再试！");
    }

    /**
     * 删除分类
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function content_del()
    {
        if (DataService::update($this->content)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

    public function teacher(){
        $id = $this->request->get('id');
        $cate = Db::name('category_module')->field('id,name')->find($id);
        $this->title = $cate['name'];
        $db = Db::name('lesson')->where(['type'=>39,'is_deleted'=>1])->order('sort asc,id asc');
        return parent::_list($db);
    }

    public function teacher_add(){
        if ($this->request->isPost()){
            $post = $this->request->post();
            $post['desc'] = json_encode(array_values($post['desc']), 320);
            $post['cover_desc'] = json_encode($post['cover_desc'], 320);
            $post['leidatu'] = json_encode(array_values($post['leidatu']), 320);
            cache('leidatu',$post['leidatu']);
            cache('desc',$post['desc']);
            $post['type'] = 39;
            Db::startTrans();
            try{
                $id = Db::name('lesson')->insertGetId($post);
                $list_data = [
                    [
                        'title'=>'培训简介',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'kechengjianjie'
                    ],
                    [
                        'title'=>'培训详情',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'kechengxiangqing'
                    ],
                    [
                        'title'=>'培训安排',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'kechenganpai'
                    ],
                    [
                        'title'=>'训前准备',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'xingqianzhunbei'
                    ],
                    [
                        'title'=>'注意事项',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'zhuyishixiang'
                    ],
                    [
                        'title'=>'安全保障',
                        'pid'=>$id,
                        'create_at'=>date('Y-m-d H:i:s'),
                        'type'=>'anquanbaozhang'
                    ],
                ];
                Db::name('lesson_content_list')->insertAll($list_data);
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $this->error('保存失败，请稍候重试！');
            }
            $this->success('保存成功！', '');
        }
        $this->assign([
            'title'=>'添加',
            'desc'=>json_decode(cache('desc'),true),
            'leidatu'=>json_decode(cache('leidatu'),true)
        ]);
        return view();
    }

    public function teacher_edit(){
        if ($this->request->isPost()){
            $post = $this->request->post();
            $post['desc'] = json_encode($post['desc'], 320);
            $post['cover_desc'] = json_encode($post['cover_desc'], 320);
            $post['leidatu'] = json_encode($post['leidatu'], 320);
            Db::name('lesson')->update($post);
            $this->success('保存成功！', '');
        }

        $id = $this->request->get('id');
        $db = \app\admin\model\Lesson::get($id)->toArray();
        $db['cover_desc'] = json_decode($db['cover_desc'], true);
        $db['desc'] = json_decode($db['desc'], true);
        $db['leidatu'] = json_decode($db['leidatu'], true);

        $this->assign([
            'db'=>$db,
            'title'=>'编辑',
        ]);
        return view();
    }
}